// 二级路由---->user--->list组件
// user-list组件
console.log('user-list组件导入了');
// 导入aixos及设置样式方法,分页器
import { axios, setStyle } from "../../../../utils/ajax.js";
import Pagination from "../../../../utils/pagination.js";
// 导入视图html结构及css样式
import { htmlStr, htmlCss } from "./view.js";

// 组件的js代码
// 获取路由入口元素
let routerView = document.querySelector('.router-view');
// 渲染
function render() {
  routerView.innerHTML = htmlStr;
  setStyle(routerView, htmlCss);
  // 组件基础内容渲染完毕后 调用
  getList();
  searchList();
  bidnEvent();

}

// 获取用户数据
async function getList() {
  let { data } = await axios({ url: '/user/list' });
  if (data.code != 1) return alert('获取用户列表失败,请重试');
  renderTbody(data.list);
}

// 事件绑定-->防抖
function searchList() {
  routerView.querySelector('input').oninput = (function (timerId) {
    return function () {
      clearTimeout(timerId);
      timerId = setTimeout(getSearchList, 500)
    }
  })()
}

// 搜索渲染
async function getSearchList() {
  let search = routerView.querySelector('input').value.trim();
  // console.log(search);
  let { data } = await axios({ url: '/user/search', params: { search } });
  if (data.code != 1) return alert('搜索用户列表失败,请重试');
  renderTbody(data.list);
}

// 分页渲染表格
function renderTbody(list) {
  // 分页器内容清空
  routerView.querySelector('.pagination').innerHTML = '';

  let pageSize = 3;
  // 实例化分页器
  new Pagination('.pagination', {
    current: 1,
    pageSize,
    total: list.length,
    change(info) {
      let { current } = info;
      // console.log('渲染数据', info, list)
      // 获取分页数据
      let users = list.slice((current - 1) * pageSize, current * pageSize);
      console.log(users);
      routerView.querySelector('tbody').innerHTML = users.reduce((prev, item, i) => {
        return prev + `
          <tr>
            <td>${i + 1}</td>
            <td>${item.username}</td>
            <td>${item.age}</td>
            <td>${item.gender}</td>
            <td><img src="http://127.0.0.1:8888/${item.avator}" style="width: 50px;height: 50px;"></td>
            <td>${item.role}</td>
            <td><button data-uid=${item._id} class='reset'>重置密码</button></td>
            <td><button data-uid=${item._id} class='flag' ${item.role == 'admin' ? 'disabled' : ''}>${item.flag ? '禁用' : '激活'}</button></td>
            <td><button data-uid=${item._id} class='del' ${item.role == 'admin' ? 'disabled' : ''} >删除</button></td>
          </tr>       
        `
      }, '')
    }
  })
}

// 绑定事件---事件委托完成
function bidnEvent() {

  routerView.querySelector('tbody').addEventListener('click', async ({ target }) => {
    if (target.className == 'reset') { // 重置密码
      let uid = target.dataset.uid;
      let { data } = await axios.post('/user/update', { uid, opt: 'reset' });
      if (data.code != 1) alert('修改失败');
      alert('修改成功');
    }
    if (target.className == 'flag') { // 禁用/激活
      let uid = target.dataset.uid;
      let val = target.innerText == '禁用' ? 0 : 1
      let { data } = await axios.post('/user/update', { uid, opt: 'flag', val });
      if (data.code != 1) return alert('修改失败');
      alert('修改成功');
      target.innerText = target.innerText == '禁用' ? '激活' : '禁用'
    }
    if (target.className == 'del') { // 删除
      if (!confirm('确定要删除?')) return
      let uid = target.dataset.uid;
      let { data } = await axios.post('/user/del', { uid });
      if (data.code != 1) alert('删除失败');
      alert('删除成功');      
      getSearchList();
    }
  })

}





export default render;